package org.esisar.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.esisar.dao.StatisticsStatementCreator;
import org.esisar.jdbc.JDBCConnector;

public class StatisticsDisplayController extends HttpServlet{

	private Connection connection;
	private PreparedStatement preparedStatement;
	private ResultSet resultSet;

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{

		if (req.getParameter("role") != null) {
			StatisticsStatementCreator stat = new StatisticsStatementCreator();
			int number = 0, average = 0;
			String surname = null;
			try {
				connection = JDBCConnector.JDBCConnector.connect();
				
				//Get the number of orders
				preparedStatement = stat.getNumberOfOrders(connection);
				resultSet = preparedStatement.executeQuery();
				while(resultSet.next()){
					number = resultSet.getInt("numberoforders");
				}
				req.setAttribute("number", number);
				
				//Get the average price of orders
				preparedStatement = stat.getAveragePrice(connection);
				resultSet = preparedStatement.executeQuery();
				while(resultSet.next()){
					average = resultSet.getInt("average");
				}
				req.setAttribute("average", average);
				
				//Get the best client
				preparedStatement = stat.getBestClient(connection);
				resultSet = preparedStatement.executeQuery();
				while(resultSet.next()){
					surname = resultSet.getString("surname");
				}
				req.setAttribute("surname", surname);
				
				RequestDispatcher dispatcher = req.getRequestDispatcher("/Statistics/Statistics.jsp");
				dispatcher.forward(req, res);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
			
	}
		
}
